﻿using System;
using System.Collections;
using UnityEngine;


namespace Utils
{
    public class TimeCoroutine: MonoSingletonBase<TimeCoroutine>
    {


        public static Coroutine Start(IEnumerator coroutine)
        {
            return Instance.StartCoroutine(coroutine);
        }
        public static void Stop(Coroutine coroutine)
        {
            if (coroutine == null) return;

            Instance.StopCoroutine(coroutine);
        }



        public static Coroutine Delay(float delayTime, Action callBack)
        {
            return Instance.StartCoroutine(Instance.IDelay(delayTime, callBack));
        }
        public static Coroutine Loop(int count, int lerpTime, Action callBack, Action finish=null)
        {
            if (count == -1)
            {
                return Instance.StartCoroutine(Instance.ILoop(lerpTime, callBack));
            }

            return Instance.StartCoroutine(Instance.ILoop(count, lerpTime, callBack, finish));
        }




        private IEnumerator IDoPlay(int duration, Action callback)
        {
            callback?.Invoke();
            yield return new WaitForSeconds(duration);
        }
        private IEnumerator ILoop(int lerp, Action callback)
        { 
            WaitForSeconds waitSec = new WaitForSeconds(lerp);

            do
            {
                callback.Invoke();
                yield return waitSec;
            }
            while (true);
        }
        private IEnumerator ILoop(int count, int lerp, Action callBack, Action finish)
        { 
            WaitForSeconds waitTime = new WaitForSeconds(lerp);   
            uint total = 0;

            callBack?.Invoke();

            do
            {
                yield return waitTime;
                total++;
                callBack?.Invoke();
            }
            while (total < count);

            finish?.Invoke();
        }
        private IEnumerator IDelay(float delayTime, Action callBack)
        {
            WaitForSeconds waitTime = new WaitForSeconds(delayTime);
            yield return waitTime;

            callBack?.Invoke();
        }
    }
}
